import 'package:flutter/material.dart';
import '../models/task.dart';
import '../theme/app_theme.dart';
import 'setting.dart';

class ProfilePage extends StatefulWidget {
  final List<Task> tasks;
  
  const ProfilePage({
    Key? key,
    required this.tasks,
  }) : super(key: key);

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> with TickerProviderStateMixin {
  // 用户信息
  final String _userName = "Steve Job";
  final String _userEmail = "SteveJob@gmail.com";
  
  // 任务分类
  late List<Map<String, dynamic>> _taskCategories;
  
  // 动画控制器
  late AnimationController _animationController;
  late AnimationController _profileAnimationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;
  late Animation<double> _scaleAnimation;
  late Animation<double> _profileScaleAnimation;

  @override
  void initState() {
    super.initState();
    _initTaskCategories();
    _initAnimations();
  }
  
  void _initAnimations() {
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 1500),
      vsync: this,
    );
    
    _profileAnimationController = AnimationController(
      duration: const Duration(milliseconds: 1200),
      vsync: this,
    );
    
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.0, 0.6, curve: Curves.easeOut),
    ));
    
    _slideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.5),
      end: Offset.zero,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.2, 0.8, curve: Curves.easeOutCubic),
    ));
    
    _scaleAnimation = Tween<double>(
      begin: 0.8,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: const Interval(0.4, 1.0, curve: Curves.elasticOut),
    ));
    
    _profileScaleAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _profileAnimationController,
      curve: Curves.elasticOut,
    ));
    
    // 启动动画
    _animationController.forward();
    _profileAnimationController.forward();
  }
  
  @override
  void dispose() {
    _animationController.dispose();
    _profileAnimationController.dispose();
    super.dispose();
  }
  
  // 初始化任务分类数据
  void _initTaskCategories() {
    final taskCounts = Task.getTaskCountByCategory(widget.tasks);
    
    _taskCategories = [
      {
        'name': 'Personal',
        'icon': Icons.person_outline,
        'color': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF8B5CF6), Color(0xFFEC4899)],
        ),
        'bgColor': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFF8F4FF), Color(0xFFFDF2F8)],
        ),
        'count': taskCounts['Personal'] ?? 0,
      },
      {
        'name': 'Work',
        'icon': Icons.work_outline,
        'color': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF3B82F6), Color(0xFF1D4ED8)],
        ),
        'bgColor': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFEFF6FF), Color(0xFFDBEAFE)],
        ),
        'count': taskCounts['Work'] ?? 0,
      },
      {
        'name': 'Private',
        'icon': Icons.lock_outline,
        'color': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFEF4444), Color(0xFFDC2626)],
        ),
        'bgColor': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFFEF2F2), Color(0xFFFEE2E2)],
        ),
        'count': taskCounts['Private'] ?? 0,
      },
      {
        'name': 'Meeting',
        'icon': Icons.people_outline,
        'color': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF10B981), Color(0xFF059669)],
        ),
        'bgColor': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFF0FDF4), Color(0xFFDCFCE7)],
        ),
        'count': taskCounts['Meeting'] ?? 0,
      },
      {
        'name': 'Events',
        'icon': Icons.event_outlined,
        'color': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFF59E0B), Color(0xFFD97706)],
        ),
        'bgColor': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFFFFBEB), Color(0xFFFEF3C7)],
        ),
        'count': taskCounts['Events'] ?? 0,
      },
      {
        'name': 'Create Board',
        'icon': Icons.add_circle_outline,
        'color': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFF6366F1), Color(0xFF8B5CF6)],
        ),
        'bgColor': const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Color(0xFFF0F9FF), Color(0xFFE0E7FF)],
        ),
        'count': 0,
        'isAction': true,
      },
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFF8FAFC),
              Color(0xFFE2E8F0),
            ],
          ),
        ),
        child: SafeArea(
          child: AnimatedBuilder(
            animation: _animationController,
            builder: (context, child) {
              return FadeTransition(
                opacity: _fadeAnimation,
                child: SlideTransition(
                  position: _slideAnimation,
        child: SingleChildScrollView(
          child: Padding(
                      padding: const EdgeInsets.all(AppTheme.paddingL),
            child: Column(
              children: [
                          // 顶部装饰区域
                          _buildTopDecoration(),
                
                // 用户资料卡
                          ScaleTransition(
                            scale: _profileScaleAnimation,
                            child: _buildUserProfileCard(),
                          ),
                          
                          // 统计概览
                          ScaleTransition(
                            scale: _scaleAnimation,
                            child: _buildStatsOverview(),
                          ),
                
                // 任务分类卡片
                          ScaleTransition(
                            scale: _scaleAnimation,
                            child: _buildTaskCategoryGrid(),
                          ),
                          
                          // 底部间距
                          const SizedBox(height: AppTheme.paddingXXL),
              ],
            ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ),
    );
  }

  // 顶部装饰区域
  Widget _buildTopDecoration() {
    return SizedBox(
      height: 60,
      child: Stack(
      children: [
          // 装饰性渐变条
          Positioned(
            top: 10,
            left: 0,
            right: 100,
            child: Container(
              height: 4,
              decoration: BoxDecoration(
                gradient: AppTheme.primaryGradient,
                borderRadius: BorderRadius.circular(2),
              ),
            ),
          ),
          // 标题
          const Positioned(
            bottom: 0,
            left: 0,
            child: Text(
              "我的",
              style: TextStyle(
                fontSize: AppTheme.fontSizeLarge,
                fontWeight: FontWeight.bold,
                color: AppTheme.textPrimaryColor,
              ),
            ),
          ),
          // 右侧操作按钮
          Positioned(
            top: 0,
            right: 0,
            child: Container(
          decoration: BoxDecoration(
                gradient: AppTheme.primaryGradient,
                borderRadius: BorderRadius.circular(AppTheme.radiusL),
            boxShadow: [
              BoxShadow(
                    color: AppTheme.primaryColor.withOpacity(0.3),
                blurRadius: 8,
                    offset: const Offset(0, 4),
              ),
            ],
          ),
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius: BorderRadius.circular(AppTheme.radiusL),
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => SettingsPage(),
                      ),
                    );
                  },
                  child: const Padding(
                    padding: EdgeInsets.all(AppTheme.paddingM),
                    child: Icon(
                      Icons.settings_outlined,
                      color: Colors.white,
                      size: 24,
                    ),
                  ),
                ),
              ),
          ),
        ),
      ],
      ),
    );
  }

  // 用户资料卡
  Widget _buildUserProfileCard() {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: AppTheme.paddingXXL),
      child: Container(
        padding: const EdgeInsets.all(AppTheme.paddingXXL),
        decoration: BoxDecoration(
          gradient: const LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [Colors.white, Color(0xFFFAFBFF)],
          ),
          borderRadius: BorderRadius.circular(AppTheme.radiusXL),
          boxShadow: [
            BoxShadow(
              color: AppTheme.primaryColor.withOpacity(0.1),
              blurRadius: 20,
              offset: const Offset(0, 8),
            ),
            BoxShadow(
              color: Colors.white.withOpacity(0.8),
              blurRadius: 20,
              offset: const Offset(0, -4),
            ),
          ],
          border: Border.all(
            color: Colors.white.withOpacity(0.6),
            width: 1,
          ),
        ),
      child: Column(
        children: [
            // 头像区域
          Container(
              width: 120,
              height: 120,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
                gradient: AppTheme.primaryGradient,
              boxShadow: [
                BoxShadow(
                    color: AppTheme.primaryColor.withOpacity(0.3),
                    blurRadius: 20,
                    offset: const Offset(0, 8),
                ),
              ],
            ),
              child: Container(
                margin: const EdgeInsets.all(4),
                decoration: const BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.white,
                ),
              child: ClipOval(
                child: Image.network(
                  'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQXnXYX3Vp5wOrEBlYpGR7FGgQgEyo-jesACCiQVvuQe-5GIENCzHLEItBlYEiJsYwQmJo&usqp=CAU',
                  fit: BoxFit.cover,
                    width: 112,
                    height: 112,
                  errorBuilder: (context, error, stackTrace) {
                      return Container(
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          gradient: AppTheme.primaryGradient,
                        ),
                        child: const Icon(
                      Icons.person,
                          size: 60,
                          color: Colors.white,
                        ),
                    );
                  },
                ),
              ),
            ),
          ),
            const SizedBox(height: AppTheme.paddingXL),
          
          // 用户名
            ShaderMask(
              shaderCallback: (bounds) => AppTheme.primaryGradient.createShader(bounds),
              child: Text(
                _userName,
                style: const TextStyle(
                  fontSize: AppTheme.fontSizeTitle + 4,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
            const SizedBox(height: AppTheme.paddingS),
            
            // 邮箱
            Container(
              padding: const EdgeInsets.symmetric(
                horizontal: AppTheme.paddingL,
                vertical: AppTheme.paddingS,
              ),
              decoration: BoxDecoration(
                color: AppTheme.primaryColor.withOpacity(0.1),
                borderRadius: BorderRadius.circular(AppTheme.radiusL),
              ),
              child: Text(
                _userEmail,
                style: const TextStyle(
                  fontSize: AppTheme.fontSizeL,
                  color: AppTheme.textSecondaryColor,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 统计概览
  Widget _buildStatsOverview() {
    final totalTasks = widget.tasks.length;
    final completedTasks = widget.tasks.where((task) => task.isCompleted).length;
    final pendingTasks = totalTasks - completedTasks;
    final completionRate = totalTasks > 0 ? (completedTasks / totalTasks * 100) : 0;

    return Container(
      margin: const EdgeInsets.only(bottom: AppTheme.paddingXXL),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            "任务概览",
            style: TextStyle(
              fontSize: AppTheme.fontSizeXL,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          const SizedBox(height: AppTheme.paddingL),
          Row(
            children: [
              Expanded(child: _buildStatCard("总任务", totalTasks.toString(), Icons.assignment_outlined, AppTheme.primaryGradient)),
              const SizedBox(width: AppTheme.paddingM),
              Expanded(child: _buildStatCard("已完成", completedTasks.toString(), Icons.check_circle_outline, AppTheme.successGradient)),
            ],
          ),
          const SizedBox(height: AppTheme.paddingM),
          Row(
            children: [
              Expanded(child: _buildStatCard("待完成", pendingTasks.toString(), Icons.pending_outlined, AppTheme.warningGradient)),
              const SizedBox(width: AppTheme.paddingM),
              Expanded(child: _buildStatCard("完成率", "${completionRate.toStringAsFixed(0)}%", Icons.trending_up_outlined, 
                completionRate >= 80 ? AppTheme.successGradient : completionRate >= 50 ? AppTheme.warningGradient : 
                const LinearGradient(colors: [Color(0xFFEF4444), Color(0xFFDC2626)]))),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard(String title, String value, IconData icon, LinearGradient gradient) {
    return Container(
      padding: const EdgeInsets.all(AppTheme.paddingL),
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [Colors.white, Color(0xFFFAFBFF)],
        ),
        borderRadius: BorderRadius.circular(AppTheme.radiusL),
        boxShadow: AppTheme.softShadow,
        border: Border.all(
          color: Colors.white.withOpacity(0.6),
          width: 1,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              gradient: gradient,
              borderRadius: BorderRadius.circular(8),
            ),
            child: Icon(
              icon,
              color: Colors.white,
              size: 20,
            ),
          ),
          const SizedBox(height: AppTheme.paddingM),
          Text(
            value,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeXL,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryColor,
            ),
          ),
          Text(
            title,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeS,
              color: AppTheme.textSecondaryColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  // 任务分类网格
  Widget _buildTaskCategoryGrid() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          "任务分类",
          style: TextStyle(
            fontSize: AppTheme.fontSizeXL,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimaryColor,
          ),
        ),
        const SizedBox(height: AppTheme.paddingL),
        GridView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2,
            crossAxisSpacing: AppTheme.paddingM,
            mainAxisSpacing: AppTheme.paddingM,
        childAspectRatio: 1.1,
      ),
      itemCount: _taskCategories.length,
      itemBuilder: (context, index) {
        final category = _taskCategories[index];
        return _buildCategoryCard(
          name: category['name'],
          icon: category['icon'],
              colorGradient: category['color'],
              bgGradient: category['bgColor'],
          count: category['count'],
          isAction: category['isAction'] ?? false,
              index: index,
        );
      },
        ),
      ],
    );
  }

  // 单个分类卡片
  Widget _buildCategoryCard({
    required String name,
    required IconData icon,
    required LinearGradient colorGradient,
    required LinearGradient bgGradient,
    required int count,
    bool isAction = false,
    required int index,
  }) {
    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 300 + (index * 100)),
      tween: Tween(begin: 0.0, end: 1.0),
      builder: (context, value, child) {
        return Transform.scale(
          scale: value,
          child: Container(
            decoration: BoxDecoration(
              gradient: bgGradient,
              borderRadius: BorderRadius.circular(AppTheme.radiusXL),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 15,
                  offset: const Offset(0, 5),
                ),
                BoxShadow(
                  color: Colors.white.withOpacity(0.9),
                  blurRadius: 15,
                  offset: const Offset(0, -2),
                ),
              ],
              border: Border.all(
                color: Colors.white.withOpacity(0.6),
                width: 1,
              ),
            ),
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                borderRadius: BorderRadius.circular(AppTheme.radiusXL),
      onTap: () {
        if (isAction) {
          // 处理创建新板块的逻辑
        } else {
          // 导航到对应分类的任务列表
        }
      },
                child: Padding(
                  padding: const EdgeInsets.all(AppTheme.paddingL),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
                      // 图标容器
            Container(
                        width: 60,
                        height: 60,
              decoration: BoxDecoration(
                          gradient: colorGradient,
                          borderRadius: BorderRadius.circular(AppTheme.radiusL),
                          boxShadow: [
                            BoxShadow(
                              color: Colors.black.withOpacity(0.1),
                              blurRadius: 10,
                              offset: const Offset(0, 4),
                            ),
                          ],
              ),
              child: Icon(
                icon,
                          color: Colors.white,
                          size: 28,
              ),
            ),
                      const SizedBox(height: AppTheme.paddingM),
            
            // 类别名称
            Text(
              name,
              style: const TextStyle(
                          fontSize: AppTheme.fontSizeL,
                fontWeight: FontWeight.bold,
                          color: AppTheme.textPrimaryColor,
              ),
                        textAlign: TextAlign.center,
            ),
            
            // 任务数量（如果不是操作按钮）
                      if (!isAction) ...[
                        const SizedBox(height: AppTheme.paddingXS),
                        Container(
                          padding: const EdgeInsets.symmetric(
                            horizontal: AppTheme.paddingM,
                            vertical: AppTheme.paddingXS,
                          ),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.8),
                            borderRadius: BorderRadius.circular(AppTheme.radiusM),
                          ),
                child: Text(
                            '$count 个任务',
                            style: const TextStyle(
                              fontSize: AppTheme.fontSizeS,
                              color: AppTheme.textSecondaryColor,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ],
                    ],
                  ),
                ),
              ),
        ),
      ),
        );
      },
    );
  }
} 